package com.bnyy.medicalHousekeeper.moudle.message.adapter;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Space;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.SpanUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.bnyy.common.adapter.BaseNormalListAdapter;
import com.bnyy.medicalHousekeeper.GlideHelper;
import com.bnyy.medicalHousekeeper.R;
import com.bnyy.medicalHousekeeper.UserInfoManager;
import com.bnyy.medicalHousekeeper.activity.ArticleDetailActivity;
import com.bnyy.medicalHousekeeper.activity.MedicalHousekeeperHomePageActivity;
import com.bnyy.medicalHousekeeper.activity.NormalGoodsDetailActivity;
import com.bnyy.medicalHousekeeper.activity.ServiceGoodsDetailActivity;
import com.bnyy.medicalHousekeeper.bean.Article;
import com.bnyy.medicalHousekeeper.bean.Goods;
import com.bnyy.medicalHousekeeper.moudle.health.activity.BloodPressureWeeklyActivity;
import com.bnyy.medicalHousekeeper.moudle.message.AudioManager;
import com.bnyy.medicalHousekeeper.moudle.message.MessageManager;
import com.bnyy.medicalHousekeeper.moudle.message.activity.GroupChatActivityDetailActivity;
import com.bnyy.medicalHousekeeper.moudle.message.activity.GroupChatVoteDetailActivity;
import com.bnyy.medicalHousekeeper.moudle.message.activity.JoinGroupChatActivity;
import com.bnyy.medicalHousekeeper.moudle.message.activity.UserHomePageActivity;
import com.bnyy.medicalHousekeeper.request.BaseObserverImpl;
import com.bnyy.medicalHousekeeper.request.RequestManager;
import com.bnyy.message.bean.ContactUser;
import com.bnyy.message.bean.chat.ChatMessage;
import com.bnyy.message.bean.chat.message_data.AlarmMessage;
import com.bnyy.message.bean.chat.message_data.ArticleMessage;
import com.bnyy.message.bean.chat.message_data.GoodsMessage;
import com.bnyy.message.bean.chat.message_data.GroupChatActivityMessage;
import com.bnyy.message.bean.chat.message_data.GroupChatVoteMessage;
import com.bnyy.message.bean.chat.message_data.HealthWeeklyMessage;
import com.bnyy.message.bean.chat.message_data.InvitationMessage;
import com.bnyy.message.bean.chat.message_data.MallGoodsMessage;
import com.bnyy.message.bean.chat.message_data.MessageData;
import com.bnyy.message.bean.chat.message_data.TipsMessage;
import com.bnyy.message.bean.chat.message_data.TipsMessageList;
import com.bnyy.message.bean.chat.message_data.UserHomePageMessage;
import com.bnyy.message.enums.ChatMessageStatus;
import com.bnyy.message.enums.MessageType;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.kevin.photo_browse.PhotoBrowse;
import com.kevin.photo_browse.ShowType;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.function.BiConsumer;

import jp.wasabeef.glide.transformations.RoundedCornersTransformation;

/**
 * Author : 关炳鹏
 * Description :
 * Date : 2022/6/29
 **/
public class ChatMessageAdapter extends BaseNormalListAdapter<ChatMessage, ChatMessageAdapter.ViewHolder> {

    private int grayLight;
    private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
    private int loginUserId,loginUserRoleId;
    private Callback callback;

    public ChatMessageAdapter(Context context, Callback callback) {
        super(context);
        this.callback = callback;
        loginUserId = UserInfoManager.getInstance().getLoginUserId();
        loginUserRoleId = UserInfoManager.getInstance().getLoginUserRoleId();
        grayLight = ContextCompat.getColor(mContext, R.color.gray_light);
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder(inflater.inflate(R.layout.item_chat_message, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        super.onBindViewHolder(holder, position);

        ChatMessage chatMessage = getData(position);

        long chatRecordTime = chatMessage.getTime();
        if (position == 0) {
            setTime(holder, chatRecordTime);
        } else {
            setTime(holder, chatRecordTime, getData(position - 1).getTime());
        }
        MessageType messageType = MessageType.getMessageType(chatMessage.getMsg_type());
        if (messageType.isTipsChatMessage()) {
            holder.llTipsRoot.setVisibility(View.VISIBLE);
            holder.llContentRoot.setVisibility(View.GONE);
            holder.llTipsRoot.removeAllViews();

            TextView tvTips = new TextView(mContext);
            tvTips.setGravity(Gravity.CENTER);
            tvTips.setTextAppearance(R.style.NormalTextView_Small);
            tvTips.setTextColor(grayLight);
            holder.llTipsRoot.addView(tvTips);

            switch (messageType) {
                case GROUP_CHAT_CREATED: // 群聊创建
                    View view = inflater.inflate(R.layout.item_message_create_group_chat, holder.llTipsRoot, true);
                    view.findViewById(R.id.iv_delete).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            MessageManager.delete(chatMessage);
                            getDatas().remove(position);
                            notifyItemRemoved(position);
                        }
                    });
                    view.findViewById(R.id.tv_invite).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            callback.addMember();
                        }
                    });

                    SpanUtils.with(tvTips)
                            .append("点击")
                            .append("去设置").setClickSpan(Color.parseColor("#48A6F8"), false, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            callback.editGroupChatName();
                        }
                    }).append("，可以更换群名称哦").create();
                    break;
                default:
                    MessageData messageData = getMessageData(chatMessage);
                    String content = chatMessage.getContent();
                    if (messageData instanceof TipsMessageList) {
                        TipsMessageList tipsMessageList = (TipsMessageList) messageData;
                        ArrayList<TipsMessage> tipsMessages = tipsMessageList.getTipsMessages();
                        if (tipsMessages.size() > 0) {
                            SpanUtils spanUtils = SpanUtils.with(tvTips);

                            for (TipsMessage tipsMessage : tipsMessages) {
                                String keyword = tipsMessage.getKeyword();
                                if (content.contains(keyword)) {
                                    String[] array = content.split(keyword);
                                    if (array.length > 1) {
                                        spanUtils.append(array[0]);
                                        spanUtils.append(keyword).setClickSpan(Color.parseColor("#48A6F8"), false, new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                switch (tipsMessage.getType()) {
                                                    case 1:
                                                        UserHomePageActivity.show(mContext, tipsMessage.getId(), tipsMessage.getRoldId());
                                                        break;
                                                    case 2:
                                                        GroupChatVoteDetailActivity.show(mContext, tipsMessage.getId());
                                                        break;
                                                    case 3:
                                                        GroupChatActivityDetailActivity.show(mContext, tipsMessage.getId());
                                                        break;
                                                }
                                            }
                                        });
                                        content = array[1];
                                    } else {
                                        if (content.length() - content.indexOf(keyword) == keyword.length()) {
                                            spanUtils.append(array[0]);
                                        } else {
                                            content = array[0];
                                        }
                                        spanUtils.append(keyword).setClickSpan(Color.parseColor("#48A6F8"), false, new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                switch (tipsMessage.getType()) {
                                                    case 1:
                                                        UserHomePageActivity.show(mContext, tipsMessage.getId(), tipsMessage.getRoldId());
                                                        break;
                                                    case 2:
                                                        GroupChatVoteDetailActivity.show(mContext, tipsMessage.getId());
                                                        break;
                                                    case 3:
                                                        GroupChatActivityDetailActivity.show(mContext, tipsMessage.getId());
                                                        break;
                                                }
                                            }
                                        });
                                    }
                                }
                            }
                            spanUtils.create();
                        } else {
                            tvTips.setText(content);
                        }
                    } else {
                        tvTips.setText(content);
                    }

                    break;
            }

        } else {
            boolean isSend = chatMessage.getSenderId() == loginUserId && chatMessage.getSenderRoleId() == loginUserRoleId;

            GlideHelper.setCircleImage(mContext, chatMessage.getUser_img(), isSend ? holder.ivSender : holder.ivReceiver, R.mipmap.icon_default_header_man);

            holder.ivReceiver.setVisibility(isSend ? View.GONE : View.VISIBLE);
            holder.ivSender.setVisibility(isSend ? View.VISIBLE : View.GONE);
            holder.tvName.setText(chatMessage.getUsername());
            holder.tvName.setVisibility(isSend ? View.GONE : View.VISIBLE);
            holder.spaceReceive.setVisibility(isSend ? View.GONE : View.VISIBLE);
            holder.spaceSend.setVisibility(isSend ? View.VISIBLE : View.GONE);

            switch (messageType) {
                case CHAT_IMAGE: // 图片
                    setChatMessageItem(holder, chatMessage, R.layout.item_message_chat_image,
                            new BiConsumer<View, ChatMessage>() {
                                @Override
                                public void accept(View view, ChatMessage chatMessage) {
                                    String imageCachePath = chatMessage.getImageCachePath();
                                    if (TextUtils.isEmpty(imageCachePath)) {
                                        imageCachePath = MessageManager.getImageCachePath(chatMessage.getContent());
                                        chatMessage.setImageCachePath(imageCachePath);
                                        MessageManager.updateMessage(chatMessage, ChatMessage.ColumnName.IMAGE_CACHE_PATH);
                                    }

                                    ImageView iv = view.findViewById(R.id.iv);
                                    iv.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {

                                            PhotoBrowse.with((Activity) mContext)
                                                    .showType(ShowType.SINGLE_URL)
                                                    .url(chatMessage.getOriginalImageUrl())
                                                    .show();
                                        }
                                    });
                                    Glide.with(mContext)
                                            .load(new File(imageCachePath))
                                            .into(new CustomTarget<Drawable>() {
                                                @Override
                                                public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                                                    int minimumWidth = resource.getMinimumWidth();
                                                    int minimumHeight = resource.getMinimumHeight();
                                                    int screenWidth = ScreenUtils.getScreenWidth();
                                                    int minWidth = screenWidth / 4;
                                                    int maxWidth = screenWidth / 3;
                                                    int width = minimumWidth;
                                                    if (minimumWidth < minWidth) {
                                                        width = minWidth;
                                                    } else if (minimumWidth > maxWidth) {
                                                        width = maxWidth;
                                                    }

                                                    ViewGroup.LayoutParams layoutParams = iv.getLayoutParams();
                                                    if (layoutParams == null) {
                                                        layoutParams = new ViewGroup.LayoutParams(0, 0);
                                                    }
                                                    layoutParams.width = width;
                                                    if (minimumHeight > (minimumWidth / 2 * 3)) {
                                                        layoutParams.height = layoutParams.width / 2 * 3;
                                                    } else {
                                                        layoutParams.height = layoutParams.width * minimumHeight / minimumWidth;
                                                    }

                                                    iv.setLayoutParams(layoutParams);
                                                    iv.setImageDrawable(resource);
                                                }

                                                @Override
                                                public void onLoadCleared(@Nullable Drawable placeholder) {

                                                }
                                            });
                                }
                            });
                    break;
                case CHAT_TEXT: // 文本
                case GROUP_CHAT_NOTICE:
                    setChatMessageItem(holder, chatMessage, isSend ? R.layout.item_message_chat_send_text : R.layout.item_message_chat_received_text,
                            new BiConsumer<View, ChatMessage>() {
                                @Override
                                public void accept(View view, ChatMessage chatMessage) {
                                    TextView tvContent = view.findViewById(R.id.tv_content);
                                    if (messageType == MessageType.GROUP_CHAT_NOTICE) {
                                        SpanUtils.with(tvContent)
                                                .append("群公告：").setBold()
                                                .appendLine()
                                                .append(chatMessage.getContent())
                                                .create();
                                    } else {
                                        tvContent.setText(chatMessage.getContent());
                                    }
                                }
                            });
                    break;
                case CHAT_AUDIO: // 语音
                    setChatMessageItem(holder, chatMessage, isSend ? R.layout.item_message_chat_send_audio : R.layout.item_message_chat_received_audio,
                            new BiConsumer<View, ChatMessage>() {
                                @Override
                                public void accept(View view, ChatMessage chatMessage) {
                                    int duration = chatMessage.getDuration();

                                    TextView tvDuraion = view.findViewById(R.id.tv_duration);
                                    tvDuraion.setText(duration + "″");

                                    int padding = 12;
                                    if (duration > 5) {
                                        padding += (duration - 5) * 5;
                                    }

                                    tvDuraion.setPadding(isSend ? SizeUtils.dp2px(padding) : 0, 0, isSend ? 0 : SizeUtils.dp2px(padding), 0);

                                    if (!isSend) {
                                        View redPoint = view.findViewById(R.id.view_red_point);
                                        redPoint.setVisibility(chatMessage.isPlayed() ? View.GONE : View.VISIBLE);
                                    }

                                    view.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            String audioCachePath = chatMessage.getAudioCachePath();
                                            if (TextUtils.isEmpty(audioCachePath)) {
                                                audioCachePath = MessageManager.getAudioCachePath(chatMessage);
                                                chatMessage.setAudioCachePath(audioCachePath);
                                                MessageManager.updateMessage(chatMessage, ChatMessage.ColumnName.IMAGE_CACHE_PATH);
                                            }

                                            if (!chatMessage.isPlayed()) {
                                                chatMessage.setPlayed(true);
                                                MessageManager.updateMessage(chatMessage, ChatMessage.ColumnName.PLAYED);

                                                View redPoint = view.findViewById(R.id.view_red_point);
                                                if (redPoint != null) {
                                                    redPoint.setVisibility(View.GONE);
                                                }
                                            }

                                            if (audioCachePath.equals(AudioManager.getInstance().getPlayingPath())) {
                                                AudioManager.getInstance().stop();
                                            } else {
                                                AnimationDrawable animationDrawable = (AnimationDrawable) v.findViewById(R.id.iv_play_audio).getBackground();
                                                startAudioAnim(animationDrawable);
                                                AudioManager.getInstance().play(audioCachePath, new AudioManager.Listener() {
                                                    @Override
                                                    public void onPrepared() {

                                                    }

                                                    @Override
                                                    public void onStop() {
                                                        stopAudioAmin(animationDrawable);
                                                    }
                                                });
                                            }
                                        }
                                    });
                                }
                            });
                    break;
                case MALL_GOODS: // 商城商品
                case SERVICE_GOODS: // 服务商品
                    setChatMessageItem(holder, chatMessage, R.layout.item_message_chat_goods,
                            new BiConsumer<View, ChatMessage>() {
                                @Override
                                public void accept(View view, ChatMessage chatMessage) {

                                    ImageView iv = view.findViewById(R.id.iv);
                                    TextView tvGoodsName = view.findViewById(R.id.tv_goods_name);
                                    TextView tvPrice = view.findViewById(R.id.tv_price);

                                    GoodsMessage goodsMessage = (GoodsMessage) getMessageData(chatMessage);

                                    if (goodsMessage != null) {
                                        tvGoodsName.setText(goodsMessage.getName());
                                        tvPrice.setText("¥" + goodsMessage.getPrice());
                                        GlideHelper.setRoundImage(mContext, goodsMessage.getImg(), iv);
                                    }

                                    view.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            if (goodsMessage != null) {
                                                switch (messageType) {
                                                    case MALL_GOODS: // 商城商品
                                                        MallGoodsMessage mallGoodsMessage = (MallGoodsMessage) goodsMessage;
//                                                        HashMap<String, Object> params = new HashMap<>();
//                                                        params.put("shop_id", mallGoodsMessage.getShop_id());
//                                                        params.put("goods_id", mallGoodsMessage.getGoodsId());
//                                                        RequestManager requestManager = RequestManager.getInstance();
//                                                        requestManager.request(requestManager.mMallRetrofitService.getGoodsDetail(RequestManager.getJsonRequestBody(params)),
//                                                                new BaseObserverImpl<GoodsDetail>(mContext) {
//                                                                    @Override
//                                                                    public void onSuccess(GoodsDetail goodsDetail) {
//                                                                        super.onSuccess(goodsDetail);
//                                                                        BaseGoodsDetailActivity.show(mContext, goodsDetail);
//                                                                    }
//                                                                });
                                                        NormalGoodsDetailActivity.show(mContext, new Goods(mallGoodsMessage.getGoodsId(), mallGoodsMessage.getShop_id()));
                                                        break;
                                                    case SERVICE_GOODS: // 服务商品
                                                        ServiceGoodsDetailActivity.show(mContext, goodsMessage.getGoodsId());
                                                        break;
                                                }
                                            }
                                        }
                                    });
                                }
                            });
                    break;
//                return new GoodsViewHolder(inflater.inflate(R.layout.item_message_chat_goods, parent, false), isSend);
                case HEALTH_ALERT: // 健康警报
//                return new WeeklyViewHolder(inflater.inflate(R.layout.item_message_chat_health_alert, parent, false), isSend);
                    setChatMessageItem(holder, chatMessage, R.layout.item_message_chat_health_alert,
                            new BiConsumer<View, ChatMessage>() {
                                @Override
                                public void accept(View view, ChatMessage chatMessage) {

                                    ImageView ivHeader = view.findViewById(R.id.iv_header);
                                    TextView tvUserName = view.findViewById(R.id.tv_user_name);
                                    TextView tvExpert = view.findViewById(R.id.tv_expert);
//
                                    HealthWeeklyMessage healthWeeklyMessage = (HealthWeeklyMessage) getMessageData(chatMessage);
                                    if (healthWeeklyMessage != null) {
                                        tvUserName.setText(healthWeeklyMessage.getUsername());
                                        tvExpert.setText("【" + healthWeeklyMessage.getDoctor_name() + "】专家发送了我的");
                                        GlideHelper.setCircleImage(mContext, healthWeeklyMessage.getUser_img(), ivHeader);
                                    }
//
                                    view.findViewById(R.id.tv_check).setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            if (healthWeeklyMessage != null) {
                                                BloodPressureWeeklyActivity.show(mContext, healthWeeklyMessage.getUser_id(), healthWeeklyMessage.getId());
                                            }
                                        }
                                    });
                                }
                            });
                    break;
                case HEALTH_WEEKLY: // 健康周报
                    setChatMessageItem(holder, chatMessage, R.layout.item_message_chat_health_weekly,
                            new BiConsumer<View, ChatMessage>() {
                                @Override
                                public void accept(View view, ChatMessage chatMessage) {

                                    ImageView ivHeader = view.findViewById(R.id.iv_header);
                                    TextView tvUserName = view.findViewById(R.id.tv_user_name);
                                    TextView tvExpert = view.findViewById(R.id.tv_expert);
//
                                    HealthWeeklyMessage healthWeeklyMessage = (HealthWeeklyMessage) getMessageData(chatMessage);
                                    if (healthWeeklyMessage != null) {
                                        tvUserName.setText(healthWeeklyMessage.getUsername());
                                        tvExpert.setText("【" + healthWeeklyMessage.getDoctor_name() + "】专家发送了我的");
                                        GlideHelper.setCircleImage(mContext, healthWeeklyMessage.getUser_img(), ivHeader);
                                    }
//
                                    view.findViewById(R.id.tv_check).setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            if (healthWeeklyMessage != null) {
                                                BloodPressureWeeklyActivity.show(mContext, healthWeeklyMessage.getUser_id(), healthWeeklyMessage.getId());
                                            }
                                        }
                                    });
                                }
                            });
                    break;
//                return new WeeklyViewHolder(inflater.inflate(R.layout.item_message_chat_weekly, parent, false), isSend);
                case ALARM: // 救援
                    setChatMessageItem(holder, chatMessage, R.layout.item_message_chat_alarm,
                            new BiConsumer<View, ChatMessage>() {
                                @Override
                                public void accept(View view, ChatMessage chatMessage) {
                                    ImageView iv = view.findViewById(R.id.iv_header);
                                    GlideHelper.setCircleImage(mContext, chatMessage.getUser_img(), iv, R.mipmap.icon_default_header_man);

                                    TextView tv = view.findViewById(R.id.tv_name);
                                    tv.setText(chatMessage.getUsername());

                                    AlarmMessage alarmMessage = (AlarmMessage) getMessageData(chatMessage);

                                    view.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            HashMap<String, String> params = new HashMap<>();
                                            params.put("alarm_uuid", alarmMessage.getAlarm_uuid());
                                            RequestManager requestManager = RequestManager.getInstance();

//                                            requestManager.request(requestManager.mAlarmJavaRetrofitService.getAlarmProcedureInfo(RequestManager.getJsonRequestBody(params)),
//                                                    new BaseObserverImpl<ArrayList<AlarmInfo>>(mContext) {
//                                                        @Override
//                                                        public void onSuccess(ArrayList<AlarmInfo> alarmInfos) {
//                                                            super.onSuccess(alarmInfos);
//                                                            if (alarmInfos.get(alarmInfos.size() - 1).getMsg_type() == AlarmSocketTag.ALARM_GROUP_FINISH) {
//                                                                AlarmLocationActivity.show(mContext, alarmInfos.get(0));
//                                                            } else {
//                                                                EventBus.getDefault().post(new AlarmEvent(AlarmEvent.Type.SWITCH_ALARM, alarmInfos.get(0)));
//                                                                MainActivity.show(mContext);
//                                                            }
//                                                        }
//                                                    });
                                        }
                                    });
                                }
                            });
                    break;
//                return new AlarmViewHolder(inflater.inflate(R.layout.item_message_chat_alarm, parent, false), isSend);
//            case FENCE: // 电子围栏
//                return new FenceViewHolder(inflater.inflate(R.layout.item_message_chat_fence, parent, false), isSend);
//            case GROUP_CHAT_NOTICE: // 群公告
//                break;
                case GROUP_CHAT_INVITATION: // 群邀请
                    setChatMessageItem(holder, chatMessage, R.layout.item_message_group_chat_invition,
                            new BiConsumer<View, ChatMessage>() {
                                @Override
                                public void accept(View view, ChatMessage chatMessage) {
                                    InvitationMessage invitationMessage = (InvitationMessage) getMessageData(chatMessage);
                                    if (invitationMessage != null) {
                                        ImageView iv = view.findViewById(R.id.iv);
                                        GlideHelper.setCircleImage(mContext, invitationMessage.getImg(), iv, R.mipmap.icon_default_header_man);

                                        TextView tvContent = view.findViewById(R.id.tv_content);
                                        SpanUtils.with(tvContent)
                                                .append(invitationMessage.getTitle())
                                                .appendLine()
                                                .appendLine()
                                                .append(invitationMessage.getContent()).setFontSize(12, true).setForegroundColor(grayLight)
                                                .create();

                                        view.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                JoinGroupChatActivity.show(mContext, invitationMessage.getId());
                                            }
                                        });

                                    }
                                }
                            });
                    break;
//                return new GroupChatInvitionViewHolder(inflater.inflate(R.layout.item_message_group_chat_invition, parent, false), isSend);
                case USER_HOMEPAGE: // 个人主页
                    setChatMessageItem(holder, chatMessage, R.layout.item_message_chat_user_home_page,
                            new BiConsumer<View, ChatMessage>() {
                                @Override
                                public void accept(View view, ChatMessage chatMessage) {
                                    UserHomePageMessage userHomePageMessage = (UserHomePageMessage) getMessageData(chatMessage);
                                    if (userHomePageMessage != null) {
                                        ContactUser contactUser = userHomePageMessage.getContactUser();
                                        if (contactUser == null) {
                                            RequestManager requestManager = RequestManager.getInstance();
                                            HashMap<String, Object> params = new HashMap<>();
                                            params.put("id", userHomePageMessage.getUser_id());
                                            params.put("role_id", userHomePageMessage.getRoleId());
                                            requestManager.request(requestManager.mMessageRetrofitService.getUserHomepage(RequestManager.getJsonRequestBody(params)),
                                                    new BaseObserverImpl<ContactUser>() {
                                                        @Override
                                                        public void onSuccess(ContactUser contactUser) {
                                                            super.onSuccess(contactUser);
                                                            UserHomePageMessage shareUserMessage = chatMessage.getMessageData(UserHomePageMessage.class);
                                                            shareUserMessage.setContactUser(contactUser);
                                                            setShareUserMessage(view, contactUser);
                                                        }
                                                    });
                                        } else {
                                            setShareUserMessage(view, contactUser);
                                        }
                                    }
                                }
                            });
                    break;
                case GROUP_CHAT_VOTE:
                    setChatMessageItem(holder, chatMessage, R.layout.item_message_chat_vote,
                            new BiConsumer<View, ChatMessage>() {
                                @Override
                                public void accept(View view, ChatMessage chatMessage) {
                                    GroupChatVoteMessage groupChatVoteMessage = (GroupChatVoteMessage) getMessageData(chatMessage);
                                    if (groupChatVoteMessage != null) {
                                        TextView tvTitle = view.findViewById(R.id.tv_title);
                                        TextView tvSubject = view.findViewById(R.id.tv_subject);

                                        tvTitle.setText(groupChatVoteMessage.getTitle());
                                        tvSubject.setText(groupChatVoteMessage.getSubject());

                                        view.findViewById(R.id.tv_vote).setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                GroupChatVoteDetailActivity.show(mContext, groupChatVoteMessage.getVote_id());
                                            }
                                        });
                                    }
                                }
                            });
                    break;
                case GROUP_CHAT_ACTIVITY:
                    setChatMessageItem(holder, chatMessage, R.layout.item_message_chat_activity,
                            new BiConsumer<View, ChatMessage>() {
                                @Override
                                public void accept(View view, ChatMessage chatMessage) {
                                    GroupChatActivityMessage groupChatActivityMessage = (GroupChatActivityMessage) getMessageData(chatMessage);
                                    if (groupChatActivityMessage != null) {
                                        TextView tvTitle = view.findViewById(R.id.tv_title);
                                        TextView tvSubject = view.findViewById(R.id.tv_subject);

                                        tvTitle.setText(groupChatActivityMessage.getTitle());
                                        tvSubject.setText(groupChatActivityMessage.getSubject());

                                        view.findViewById(R.id.tv_join).setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                GroupChatActivityDetailActivity.show(mContext, groupChatActivityMessage.getActivity_id());
                                            }
                                        });
                                    }
                                }
                            });
                    break;
                case ARTICLE:
                    setChatMessageItem(holder, chatMessage, R.layout.item_message_chat_article,
                            new BiConsumer<View, ChatMessage>() {
                                @Override
                                public void accept(View view, ChatMessage chatMessage) {
                                    ArticleMessage articleMessage = (ArticleMessage) getMessageData(chatMessage);
                                    if (articleMessage != null) {
                                        LinearLayout llArticleRoot = view.findViewById(R.id.ll_acticle_root);
                                        llArticleRoot.setGravity(isSend ? Gravity.END : Gravity.START);
                                        TextView tvArticleTitle = view.findViewById(R.id.tv_article_title);
                                        TextView author = view.findViewById(R.id.tv_author);
                                        ImageView ivAuthor = view.findViewById(R.id.iv_author);
                                        ImageView iv = view.findViewById(R.id.iv_acticle_image);

                                        tvArticleTitle.setText(articleMessage.getTitle());
                                        author.setText(articleMessage.getAuthorName());
                                        GlideHelper.setHeader(mContext, articleMessage.getAuthorImage(), ivAuthor);
//                                        GlideHelper.setRoundImage(mContext, articleMessage.getAuthorImage(), iv);

                                        Glide.with(mContext)
                                                .load(GlideHelper.getGlideUrl(articleMessage.getCoverImage()))
                                                .apply(RequestOptions.bitmapTransform(new MultiTransformation<>(
                                                        new CenterCrop(),
                                                        new RoundedCornersTransformation(SizeUtils.dp2px(10), 0, RoundedCornersTransformation.CornerType.TOP))))
                                                .into(iv);
                                        view.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                Article article = new Article(articleMessage.getShareId(), articleMessage.getTitle(), articleMessage.getCoverImage());
                                                ArticleDetailActivity.showByShareId(mContext, article);
                                            }
                                        });
                                    }
                                }
                            });
                    break;
            }
        }
    }

    private MessageData getMessageData(ChatMessage chatMessage) {
        if (chatMessage.getMessageData() == null) {
            chatMessage.setMessageData(MessageManager.getMessageData(chatMessage.getMessageType(), chatMessage.getMsgId()));
        }
        return chatMessage.getMessageData();
    }

    private void setShareUserMessage(View view, ContactUser contactUser) {
        ImageView iv = view.findViewById(R.id.iv);
        GlideHelper.setCircleImage(mContext, contactUser.getUser_img(), iv, R.mipmap.icon_default_header_man);

        TextView tvName = view.findViewById(R.id.tv_name);
        tvName.setText(contactUser.getUsername());

        TextView tvSign = view.findViewById(R.id.tv_sign);
        if (TextUtils.isEmpty(contactUser.getBrief())) {
            tvSign.setText("暂无简介");
        } else {
            tvSign.setText(contactUser.getBrief());
        }

        TextView tvLikeCount = view.findViewById(R.id.tv_like_count);
        tvLikeCount.setText(contactUser.getLikes_number() + "\n被赞");
        TextView tvFansCount = view.findViewById(R.id.tv_fans_count);
        tvFansCount.setText(contactUser.getFans_number() + "\n粉丝");

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (contactUser.getRole_id() == 2) {
                    UserHomePageActivity.show(mContext, contactUser.getId(), contactUser.getRole_id());
                } else {
                    MedicalHousekeeperHomePageActivity.show(mContext, contactUser.getId());
                }
            }
        });
    }

    private void setChatMessageItem(ViewHolder holder, ChatMessage chatMessage, int itemLayoutId, BiConsumer<View, ChatMessage> consumer) {
        boolean isSend = chatMessage.getSenderId() == loginUserId && chatMessage.getSenderRoleId() == loginUserRoleId;

        holder.llTipsRoot.setVisibility(View.GONE);
        holder.llContentRoot.setVisibility(View.VISIBLE);
        int id = chatMessage.getMsg_type() * chatMessage.getSenderId();
        Log.e("setItem", "isSend = " + isSend + " " + chatMessage.getMessageType().getName() + " " + id);
        View view = holder.llContent.findViewById(id);
        if (view == null) {
            holder.llContent.removeAllViews();
            view = inflater.inflate(itemLayoutId, holder.llContent, true);
            view.setId(id);
        }


        if (isSend) {
            ImageView ivSendFailure = view.findViewById(R.id.iv_send_failure);
            if (ivSendFailure != null) {
                ChatMessageStatus chatMessageStatus = chatMessage.getChatMessageStatus();
                ivSendFailure.setVisibility(chatMessageStatus == ChatMessageStatus.FAILURE ? View.VISIBLE : View.GONE);
                ivSendFailure.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        callback.resendMessage(chatMessage.getMsgId());
                    }
                });
            }
        }

        Space space = new Space(mContext);
        LinearLayout.LayoutParams spaceLayoutParams = new LinearLayout.LayoutParams(0, 0);
        spaceLayoutParams.weight = 1;
        holder.llContent.addView(space, isSend ? 0 : 1, spaceLayoutParams);

        consumer.accept(view, chatMessage);
    }

    private void setTime(ViewHolder holder, long chatRecordTime, long lastChatRecordTime) {
        if (chatRecordTime - lastChatRecordTime > 5 * 60 * 1000) {
            setTime(holder, chatRecordTime);
        } else {
            if (holder.tvTime.getVisibility() == View.VISIBLE) {
                holder.tvTime.setVisibility(View.GONE);
            }
        }
    }

    private void setTime(ViewHolder holder, long chatRecordTime) {
        holder.tvTime.setVisibility(View.VISIBLE);
        Date date = new Date(chatRecordTime);
        if (TimeUtils.isToday(chatRecordTime)) {
            holder.tvTime.setText(sdf.format(date));
        } else {
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            int x = calendar.get(Calendar.DAY_OF_YEAR);

            calendar.setTimeInMillis(chatRecordTime);
            int y = calendar.get(Calendar.DAY_OF_YEAR);

            if (x - y == 1) {
                holder.tvTime.setText("昨天 " + sdf.format(date));
            } else {
                holder.tvTime.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(date));
            }
        }
    }

    private void startAudioAnim(AnimationDrawable animationDrawable) {
        if (animationDrawable != null && !animationDrawable.isRunning()) {
            animationDrawable.start();
        }
    }

    private void stopAudioAmin(AnimationDrawable animationDrawable) {
        if (animationDrawable != null && animationDrawable.isRunning()) {
            animationDrawable.selectDrawable(0);
            animationDrawable.stop();
        }
    }

    static class ViewHolder extends BaseNormalListAdapter.ViewHolder {
        LinearLayout llTipsRoot;
        TextView tvTips;
        TextView tvTime;
        TextView tvName;
        LinearLayout llContentRoot;
        LinearLayout llContent;
        ImageView ivReceiver, ivSender;
        Space spaceSend, spaceReceive;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            llTipsRoot = itemView.findViewById(R.id.ll_tips_root);
            tvTips = itemView.findViewById(R.id.tv_tips);
            tvTime = itemView.findViewById(R.id.tv_time);
            tvName = itemView.findViewById(R.id.tv_name);
            ivReceiver = itemView.findViewById(R.id.iv_receiver);
            ivSender = itemView.findViewById(R.id.iv_sender);
            llContentRoot = itemView.findViewById(R.id.ll_content_root);
            llContent = itemView.findViewById(R.id.ll_content);
            spaceSend = itemView.findViewById(R.id.space_send);
            spaceReceive = itemView.findViewById(R.id.space_receive);
        }
    }

    public interface Callback {

        void resendMessage(String msgId);

        void editGroupChatName();

        void addMember();
    }
}






















